interface colorList {
  [key: string]: number
}

export default function () {
  function getBackgroundColor(img: HTMLImageElement) {
    const canvas = document.createElement('canvas')
    canvas.width = img.width
    canvas.height = img.height
    const ctx = canvas.getContext('2d')
    // 存储颜色列表
    const colorList: colorList = {}
    if (ctx) {
      ctx.drawImage(img, 0, 0, img.width, img.height)
      const imgData = ctx.getImageData(0, 0, img.width, img.height).data
      let i = 0
      while (i < imgData.length) {
        const r = imgData[i]
        const g = imgData[i + 1]
        const b = imgData[i + 2]
        const a = imgData[i + 3]
        i = i + 4
        const color = [r, g, b, a].join(',')
        if (!colorList[color]) {
          colorList[color] = 0
        }
        colorList[color]++
      }
    } else {
      return false
    }
    const colorArray = Object.entries(colorList)
    colorArray.sort((a, b) => {
      return b[1] - a[1]
    })
    const result: string[] = []
    for (const item of colorArray.splice(0, 9)) {
      result.push(item[0])
    }
    return result
  }

  function getComplementaryColor(color: string) {
    const arr = color.split(',')
    const r = parseInt(arr[0])
    const g = parseInt(arr[1])
    const b = parseInt(arr[2])
    const a = parseInt(arr[3])

    // 计算每个颜色通道的补色
    let complementaryR = r < 128 ? r + 128 : r - 128
    let complementaryG = g < 128 ? g + 128 : g - 128
    let complementaryB = b < 128 ? b + 128 : b - 128

    // 透明度通道保持不变
    const complementaryA = a

    // 确保补色的值在0到255之间
    complementaryR = Math.min(Math.max(complementaryR, 0), 255)
    complementaryG = Math.min(Math.max(complementaryG, 0), 255)
    complementaryB = Math.min(Math.max(complementaryB, 0), 255)

    return [complementaryR, complementaryG, complementaryB, complementaryA].join(',')
  }

  return {
    getBackgroundColor,
    getComplementaryColor
  }
}
